package autohotkeyide;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

/**
 * @author sad
 */
public class ImageViewer extends JPanel {

    public BufferedImage image;
    public Point hotSpot;
    public String path;

    public ImageViewer(File imageConfigFile) {
        SelectedRegion region = SelectedRegion.load(imageConfigFile);
        init(region);
    }

    private void init(SelectedRegion region) {
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        try {
            this.path = region.calculateImagePath().getAbsolutePath();
            this.hotSpot = region.getHotSpot();
            image = ImageIO.read(new File(path));
            ExtRectangle imageRectangle = new ExtRectangle(0, 0, image.getWidth(), image.getHeight());
            imageRectangle.fitProportional(new Rectangle(0, 0, 150, 40));
            Dimension d = new Dimension((int) imageRectangle.getWidth(), 40);
            setPreferredSize(d);
            setMinimumSize(d);
            setMaximumSize(d);
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        ExtRectangle imageRectangle = new ExtRectangle(0, 0, image.getWidth(), image.getHeight());
        imageRectangle.fitProportional(new Rectangle(0, 0, getWidth(), getHeight()));
        int x = (int) (getWidth() / 2.0 - imageRectangle.getWidth() / 2.0);
        int y = (int) (getHeight() / 2.0 - imageRectangle.getHeight() / 2.0);
        g.drawImage(image, x, y, (int) imageRectangle.getWidth(), (int) imageRectangle.getHeight(), this);
    }

    @Override
    public String toString() {
        return String.format("\"%s\", \"%s\", %d, %d, \"%s\"", "[--[", path, hotSpot.x, hotSpot.y, "]--]");
    }
}
